package models

import (
	"fmt"
	"football/src/utils"

	"gorm.io/gorm"
)

type RecuBasic struct {
	Index              string `json:"index" gorm:"primaryKey"`               // 唯一ID
	EventId            string `json:"event_id" gorm:"column:event_id"`       // 比赛ID
	StrateGyId         string `json:"strategy_id" gorm:"column:strategy_id"` //
	EV                 string `json:"EV" gorm:"column:EV"`                   //
	Profit             string `json:"profit" gorm:"column:profit"`
	StrategyRecuStatus string `json:"strategy_recu_status" gorm:"column:strategy_recu_status"`
	BetRecuStatus      string `json:"bet_recu_status" gorm:"bet_recu_status"`
}

type RecuContent struct {
	RecuID     int    `db:"recu_id" json:"recu_id"`         // 收据编号
	StrategyID string `db:"strategy_id" json:"strategy_id"` // 策略编号
	EventID    string `db:"event_id" json:"event_id"`       // 事件ID
	Dealer     string `db:"dealer" json:"dealer"`           // 交易商
	BetType    string `db:"bettype" json:"bettype"`         // 投注类型
	Handicap   string `db:"handicap" json:"handicap"`       // 让分
	Odd        string `db:"odd" json:"odd"`                 // 赔率
	Amount     string `db:"amount" json:"amount"`           // 投注金额
	Currency   string `db:"Currency" json:"currency"`       // 货币
	BetStatus  string `db:"bet_status" json:"bet_status"`   // 投注状态
	HomeResult string `db:"home_result" json:"home_result"` // 主队结果
	AwayResult string `db:"away_result" json:"away_result"` // 客队结果
	Reward     string `db:"reward" json:"reward"`           // 奖励金额
	Other      string `db:"other" json:"other"`             // 其他信息
}

func (table *RecuContent) TableName() string {
	return "recu_content"
}
func (table *RecuBasic) TableName() string {
	return "recu"
}

func GetOnlineStrategyList(page int, limit int) ([]*RecuBasic, int, error) {

	query := utils.CalculateData.Model(&RecuBasic{})

	return utils.Paginate[RecuBasic](query, page, limit)
}

type StrategyRate struct {
	Strategy      string
	ProfitRate    float64
	StrategyCount int
	MaxDrawdown   float64
}

func GetStrategyMonitor(db *gorm.DB) ([]StrategyRate, error) {
	// 策略名称字典
	strategyNameDict := map[string]string{
		"tips":      "专家推荐",
		"ziwang":    "主场强队",
		"zgclplus":  "杀零球",
		"arbitrage": "套利",
		"pingshou":  "平手策略",
	}

	// 第一个查询以获取策略和利润率
	query1 := `
		SELECT 
			a.strategy, 
			CAST(c.profit_rate AS DOUBLE) AS profit_rate, 
			b.strategy_count 
		FROM 
			(SELECT SUBSTRING_INDEX(strategy_id, '_', 1) AS strategy 
			 FROM recu 
			 WHERE strategy_recu_status = 1 
			 GROUP BY strategy) a 
		JOIN 
			(SELECT SUBSTRING_INDEX(strategy_id, '_', 1) AS strategy, 
				 COUNT(strategy_id) AS strategy_count 
			 FROM recu 
			 WHERE strategy_recu_status = 1 
			 GROUP BY strategy) b 
		ON a.strategy = b.strategy 
		JOIN 
			(SELECT SUBSTRING_INDEX(strategy_id, '_', 1) AS strategy, 
				 ROUND((SUM(reward) - SUM(amount)) / SUM(amount), 2) * 100 AS profit_rate 
			 FROM recu_content 
			 WHERE home_result IS NOT NULL 
			   AND away_result IS NOT NULL 
			 GROUP BY strategy) c 
		ON a.strategy = c.strategy;`

	var strategyRateCount []StrategyRate
	if err := db.Raw(query1).Scan(&strategyRateCount).Error; err != nil {
		return nil, fmt.Errorf("query failed: %w", err)
	}

	// 第二个查询以获取每日数据
	query2 := `
		SELECT 
			SUBSTRING_INDEX(strategy_id, '_', 1) AS strategy, 
			SUBSTRING_INDEX(SUBSTRING_INDEX(event_id, 'D', -1), 'T', 1) AS date, 
			SUM(amount) AS daily_amount, 
			SUM(reward) AS daily_reward 
		FROM recu_content 
		WHERE reward IS NOT NULL 
		GROUP BY strategy, date 
		ORDER BY strategy, date;`

	// 存储每日数据
	rows2, err := db.Raw(query2).Rows()
	if err != nil {
		return nil, fmt.Errorf("query failed: %w", err)
	}
	defer rows2.Close()

	// 处理每日数据
	dailyData := make(map[string][]float64) // strategy => [amount, reward]
	for rows2.Next() {
		var strategy, date string
		var dailyAmount, dailyReward float64
		if err := rows2.Scan(&strategy, &date, &dailyAmount, &dailyReward); err != nil {
			utils.Error("", err)
			continue
		}
		dailyData[strategy] = append(dailyData[strategy], dailyAmount, dailyReward)
	}

	drawdownMap := make(map[string]float64)
	for strategy, values := range dailyData {
		var cumAmount float64
		var cumReward float64
		var minRatio float64 = 999 // 设置为很大的数
		for i := 0; i < len(values); i += 2 {
			cumAmount += values[i]
			cumReward += values[i+1]
			if cumAmount > 0 {
				ratio := cumReward / cumAmount
				if ratio != 0 && ratio < minRatio {
					minRatio = ratio
				}
			}
		}
		drawdownMap[strategy] = minRatio
	}

	// 更新数据，使用策略名称字典
	for i := range strategyRateCount {
		strategy := strategyRateCount[i].Strategy
		maxDrawdownValue := drawdownMap[strategy]
		strategyRateCount[i].MaxDrawdown = maxDrawdownValue

		// 更新策略名称
		strategyRateCount[i].Strategy = strategyNameDict[strategy]
	}

	return strategyRateCount, nil
}
